package com.sinaapp.gavinzhang.GSpider.http.servlet;

import com.sinaapp.gavinzhang.GSpider.http.Tools;
import com.sinaapp.gavinzhang.GSpider.http.annotation.ServletClass;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Gavin on 2015-11-22.
 */
@ServletClass(requestName = "/search",function = "doGet")
public class SearchServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(SearchServlet.class);
    /**
     * 写在这里的代码都是 POST 请求
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String query = request.getParameter("query");

        LOGGER.info(String.format("receive query: %s", query));

        String result = "welcome to my server. It's a POST request.";
        if (null != query && !query.trim().equals("")) {
            result = query + ", " + result;
        }
        LOGGER.info(String.format("response is: %s", result));

        Tools.printToJson(result, response);
    }

    /**
     * 写在这里的代码都是 GET 请求
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String query = request.getParameter("query");

        LOGGER.info(String.format("receive query: %s", query));

        String result = "welcome to my server. It's a GET request.";
        if (null != query && !query.trim().equals("")) {
            result = query + ", " + result;
        }
        LOGGER.info(String.format("response is: %s", result));

        Tools.printToJson(result, response);
    }
}

